package com.awise.app.cloudy.activity;


import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.media.MediaPlayer;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.content.LocalBroadcastManager;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.CheckBox;
import android.widget.MediaController;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.SeekBar;
import android.widget.Switch;
import android.widget.TextView;
import android.widget.TimePicker;
import android.widget.Toast;
import android.widget.VideoView;

import com.awise.R;
import com.awise.base.BaseActivity;
import com.awise.http.RoverGlobal;
import com.awise.util.Constant;

/**
 * Created by lgz on 2018/1/23.
 */

public class CloudyActivity extends BaseActivity implements View.OnClickListener, SeekBar
        .OnSeekBarChangeListener, TimePicker.OnTimeChangedListener {
    private VideoView videoView ;
    private RelativeLayout rllayout ;
    private TextView tv_start_time,tv_end_time,tv_speed_count,tv_strength_count,tv_repeat_content;
    private RelativeLayout rl_start_time_layout,rl_end_time_layout,rl_repeat_layout,rl_onoff_switch_layout;
    private SeekBar sb_strength_seekbar,sb_speed_seekbar;
    private Switch on_off;
    private CheckBox bt_cloudy_preview_mode;
    private  boolean week_7,week_1,week_2,week_3,week_4,week_5,week_6;
    private int  time,tempTime;
    private int startTime=0,endTime=1439;
    private byte starthour=0,starminute=0,endhour=23, endmimute=59;
    private TextView tv_save;
    private int strengthProgress=0,speedProgress=1;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.cloudy_layout);
        initView();
        readData();
        String DisplayMode= getIntent().getStringExtra("DisplayMode");
        if (!TextUtils.isEmpty(DisplayMode)) {
            rl_start_time_layout.setVisibility(View.INVISIBLE);
            rl_end_time_layout.setVisibility(View.INVISIBLE);
            rl_repeat_layout.setVisibility(View.GONE);
            rl_repeat_layout.setVisibility(View.GONE);
            rl_onoff_switch_layout.setVisibility(View.INVISIBLE);
            tv_save.setVisibility(View.GONE);
        }
        showLoadingView();
        LocalBroadcastManager.getInstance(this).registerReceiver(broadcastReceiver, new IntentFilter(Constant.CLOUDY_ACTION));
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        LocalBroadcastManager.getInstance(this).unregisterReceiver(broadcastReceiver);
    }

    private void initView() {
        videoView = (VideoView)this.findViewById(R.id.cloudy_videoView );
        rllayout = (RelativeLayout)this.findViewById(R.id.cloudy_rl_vv_layout );
        rl_start_time_layout = (RelativeLayout)this.findViewById(R.id.rl_start_time_layout );
        rl_end_time_layout = (RelativeLayout)this.findViewById(R.id.rl_end_time_layout );
        rl_repeat_layout = (RelativeLayout)this.findViewById(R.id.rl_repeat_layout );
        rl_onoff_switch_layout = (RelativeLayout)this.findViewById(R.id.rl_onoff_switch_layout );
        sb_strength_seekbar = (SeekBar)this.findViewById(R.id.sb_strength_seekbar );
        sb_speed_seekbar = (SeekBar)this.findViewById(R.id.sb_speed_seekbar );
        tv_start_time=(TextView)this.findViewById(R.id.tv_start_time );
        tv_end_time=(TextView)this.findViewById(R.id.tv_end_time );
        tv_speed_count=(TextView)this.findViewById(R.id.tv_speed_count );
        tv_strength_count=(TextView)this.findViewById(R.id.tv_strength_count );
        tv_repeat_content=(TextView)this.findViewById(R.id.tv_repeat_content );
        on_off=(Switch)this.findViewById(R.id.on_off );
        bt_cloudy_preview_mode=(CheckBox)this.findViewById(R.id.bt_cloudy_preview_mode);
        bt_cloudy_preview_mode.setOnClickListener(this);
        TextView s_back = (TextView) this.findViewById(R.id.tv_back);
        TextView  textView_content = (TextView) this.findViewById(R.id.textView_content);
        textView_content.setText(R.string.cloudy_title);
        tv_save = (TextView) this.findViewById(R.id.tv_save);
        tv_save.setVisibility(View.VISIBLE);
        tv_save.setOnClickListener(this);
        s_back.setVisibility(View.VISIBLE);
        s_back.setOnClickListener(this);
        rl_start_time_layout.setOnClickListener(this);
        rl_end_time_layout.setOnClickListener(this);
        sb_strength_seekbar.setOnSeekBarChangeListener(this);
        sb_speed_seekbar.setOnSeekBarChangeListener(this);
        rl_repeat_layout.setOnClickListener(this);
        RelativeLayout.LayoutParams layoutParams= (RelativeLayout.LayoutParams) rllayout.getLayoutParams();
        layoutParams.addRule(RelativeLayout.ALIGN_PARENT_BOTTOM);
        layoutParams.addRule(RelativeLayout.ALIGN_PARENT_TOP);
        layoutParams.addRule(RelativeLayout.ALIGN_PARENT_LEFT);
        layoutParams.addRule(RelativeLayout.ALIGN_PARENT_RIGHT);
        videoView.setLayoutParams(layoutParams);
         Uri uri = Uri.parse( "android.resource://com.awise/" +R.raw.cloudy );
        MediaController   mediaCtlr = new MediaController(CloudyActivity.this);
        mediaCtlr.setMediaPlayer(videoView);
        mediaCtlr.setVisibility(View.INVISIBLE); //设置隐藏
        videoView.setMediaController(mediaCtlr); // 设置视频控制器
        videoView.setOnCompletionListener( new MyPlayerOnCompletionListener());// 播放完成回调
        videoView.setVideoURI(uri); // 设置视频路径
        videoView.start(); // 开始播放视频
//        tv_start_time.setText("00:00");
//        tv_end_time.setText("23:59");
        tv_speed_count.setText(speedProgress+getString(R.string.greed));
        on_off.setOnClickListener(this);
    }
    private   byte onoffvalue=(byte) 0x00;

    @Override
    public void onClick(View view) {
        switch (view.getId()){
            case R.id.tv_back:
                if (bt_cloudy_preview_mode.isChecked()){
                    stopPreviewMode();
                }
                finish();
                break;
            case R.id.on_off:
//             (开)/0x00（关）
                onoffvalue=on_off.isChecked()?(byte) 0x01:(byte) 0x00;
                onoff(onoffvalue);
                break;
            case R.id.bt_cloudy_preview_mode:
                if (bt_cloudy_preview_mode.isChecked()){
                    bt_cloudy_preview_mode.setText(R.string.stop_preview_mode);
                    startPreviewMode();
                }else {
                    bt_cloudy_preview_mode.setText(R.string.preview_mode);
                    stopPreviewMode();
                }
                break;
            case R.id.tv_save:
                int weekValue = 0;
                if(week_1) {
                    weekValue += 1;
                }
                if(week_2) {
                    weekValue += (1 << 1);
                }
                if(week_3) {
                    weekValue += (1 << 2);
                }
                if(week_4) {
                    weekValue += (1 << 3);
                }
                if(week_5) {
                    weekValue += (1 << 4);
                }
                if(week_6) {
                    weekValue += (1 << 5);
                }
                if(week_7) {
                    weekValue += (1 << 6);
                }
                setDownLoad((byte) weekValue,(byte)speedProgress, (byte)strengthProgress,starthour,starminute,endhour, endmimute);
                showlaoddingwindow();
                break;
            case R.id.rl_start_time_layout:
                time=1;
                showPopupWindow();
                break;
            case R.id.rl_end_time_layout:
                time=2;
                showPopupWindow();
                break;
            case R.id.rl_repeat_layout:
                startActivityForResult(new Intent(this,RepeatDayActivity.class)
                        .putExtra("week_7",week_7)
                        .putExtra("week_1",week_1)
                        .putExtra("week_2",week_2)
                        .putExtra("week_3",week_3)
                        .putExtra("week_4",week_4)
                        .putExtra("week_5",week_5)
                        .putExtra("week_6",week_6),111);
                break;
        }
    }
    @Override
    public void onProgressChanged(SeekBar seekBar, int progress, boolean b) {
        if (seekBar.equals(sb_strength_seekbar)){
            tv_strength_count.setText(progress+"%");
            strengthProgress=progress;
        }else if (seekBar.equals(sb_speed_seekbar)){
            speedProgress=progress+1;
            tv_speed_count.setText(speedProgress+getString(R.string.greed));
        }
    }

    @Override
    public void onStartTrackingTouch(SeekBar seekBar) {

    }

    @Override
    public void onStopTrackingTouch(SeekBar seekBar) {

    }
    @Override
    public void onTimeChanged(TimePicker timePicker, int hourOfDay, int minute) {
        switch (time) {
            case 1:
                tempTime=hourOfDay*60+minute;
                if (tempTime<endTime&&tempTime!=1439){
                    String  startHourTime=(hourOfDay<10)?("0"+hourOfDay):(""+hourOfDay);
                    String  startMinuteTime=(minute<10)?("0"+minute):(""+minute);
                    tv_start_time.setText(startHourTime+":"+startMinuteTime);
                    startTime=hourOfDay*60+minute;
                    starthour=(byte)hourOfDay;
                    starminute=(byte)minute;
                } else {
                    Toast.makeText(CloudyActivity.this, R.string.time_tips, Toast.LENGTH_SHORT).show();
                }
                break;
            case 2:
                tempTime=hourOfDay*60+minute;
                if (tempTime>startTime&&tempTime!=0) {
                    String  endHourTime=(hourOfDay<10)?("0"+hourOfDay):(""+hourOfDay);
                    String  endMinuteTime=(minute<10)?("0"+minute):(""+minute);
                    tv_end_time.setText(endHourTime+":"+endMinuteTime);
                    endTime=hourOfDay*60+minute;
                    endhour=(byte)hourOfDay;
                    endmimute=(byte)minute;
                } else {
                    Toast.makeText(CloudyActivity.this, R.string.time_tips, Toast.LENGTH_SHORT).show();
                }
                break;
            default:
                break;
        }
    }

    class MyPlayerOnCompletionListener implements MediaPlayer.OnCompletionListener {
         @Override
         public void onCompletion(MediaPlayer mp) {
             videoView.start();
             mp.setLooping(true);
         }
    }

    @Override
    protected void onStart() {
        super.onStart();
        if (videoView!=null)
            videoView.start(); // 开始播放视频
    }

    private PopupWindow mPopWindow;
    private StringBuffer  buffer;
    private void showPopupWindow() {
        //设置contentView
        View contentView = LayoutInflater.from(this).inflate(R.layout.cloudy_timer_pop_layout, null);
        mPopWindow = new PopupWindow(contentView,
                RelativeLayout.LayoutParams.MATCH_PARENT, RelativeLayout.LayoutParams.WRAP_CONTENT, true);
        //设置各个控件的点击响应
        TimePicker timePicker= (TimePicker)contentView.findViewById(R.id.timePicker);
        timePicker.setIs24HourView(true);
        timePicker.setOnTimeChangedListener(this);
        timePicker.setOnClickListener(this);
        //显示PopupWindow
        View rootview = LayoutInflater.from(this).inflate(R.layout.cloudy_layout, null);
        mPopWindow.showAtLocation(rootview, Gravity.BOTTOM, 0, 0);

    }
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode==111&&resultCode==RESULT_OK){
             week_7 =data.getBooleanExtra("week_7",false);
             week_1 =data.getBooleanExtra("week_1",false);
             week_2 =data.getBooleanExtra("week_2",false);
             week_3 =data.getBooleanExtra("week_3",false);
             week_4 =data.getBooleanExtra("week_4",false);
             week_5 =data.getBooleanExtra("week_5",false);
             week_6 =data.getBooleanExtra("week_6",false);
            buffer=new StringBuffer();
            if (week_1)
                buffer.append(getString(R.string.week_1));
            if (week_2)
                buffer.append(getString(R.string.week_2));
            if (week_3)
                buffer.append(getString(R.string.week_3));
            if (week_4)
                buffer.append(getString(R.string.week_4));
            if (week_5)
                buffer.append(getString(R.string.week_5));
            if (week_6)
                buffer.append(getString(R.string.week_6));
            if (week_7)
                buffer.append(getString(R.string.week_7));
            if (week_1&&week_2&&week_3&&week_4&&week_5&&week_6&&week_7){
                buffer=new StringBuffer();
                buffer.append(getString(R.string.week_all));
            }
            tv_repeat_content.setText(buffer);
        }
    }
    private void onoff(byte value) {
//     0xC0 0x0A   0x11	0x01	0x13	0xxx	0x00 0x01	0x01(开)/0x00（关）0x00
        byte[] bytes = {(byte) 0xc0, 0x0a, 0x11, 0x01, 0x13, 0x32, 0x00, 0x01, value, 0x00};
        bytes[bytes.length - 1] = RoverGlobal.getInstance().getAddValue(bytes, bytes.length);
        RoverGlobal.getInstance().connect.write(bytes);
    }


    public void setDownLoad(byte weekday, byte progress1, byte progress2, byte starthour, byte starminute, byte endhour, byte endmimute   ) {
//        System.out.println("value1:"+weekday+"  "+progress1+"  "+progress2+"  "+starthour+" "+starminute+" "+endhour+" "+endmimute);
        byte[] bytes = {(byte) 0xc0, 0x0a, 0x11, 0x01, 0x17, 0x00, 0x00, 0x08, onoffvalue, weekday,
                progress1,progress2,starthour,starminute,endhour,endmimute, 0x00};
        bytes[bytes.length-1] = RoverGlobal.getInstance().getAddValue(bytes, bytes.length);
        RoverGlobal.getInstance().connect.write(bytes);
//        多云模式下载（开始时间01:01、 结束时间02:02、 速度8级、 亮度100%、全周重复、 开启）
//        c0 0a 11 01 17 00 00 08 01开关 7f星期 08 64 01 01 02 02 ？
    }

    public   void  startPreviewMode(){
     /*   预览多云  c0 0a 11 01 19 01 00 02 64 64 c0*/
        byte[] bytes = {(byte) 0xc0, 0x0a, 0x11, 0x01, 0x19, 0x01, 0x00, 0x02,(byte)speedProgress, (byte)strengthProgress, 0x00};
        bytes[bytes.length-1] = RoverGlobal.getInstance().getAddValue(bytes, bytes.length);
        RoverGlobal.getInstance().connect.write(bytes);
    }

    //读取数据
    private void readData() {
        byte[] bytes = {(byte) 0xc0, 0x0a, 0x11, 0x01, 0x1a, 0x39, 0x00, 0x00, 0x00};
        bytes[bytes.length - 1] = RoverGlobal.getInstance().getAddValue(bytes, bytes.length);
        RoverGlobal.getInstance().connect.write(bytes);
    }

    public  void stopPreviewMode(){
//        0xC0 0x0A	0x11	0x01	0x33	0x00	0x00 0x00
        byte[] bytes = {(byte) 0xc0, 0x0a, 0x11, 0x01, 0x33, 0x00, 0x00, 0x00, 0x00};
        bytes[bytes.length-1] = RoverGlobal.getInstance().getAddValue(bytes, bytes.length);
        RoverGlobal.getInstance().connect.write(bytes);

    }

    StringBuffer  buffers;
    private BroadcastReceiver broadcastReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            closedLoadingView();
            if (intent.getAction() == Constant.CLOUDY_ACTION) {
                byte[] buffer = intent.getByteArrayExtra("socket_data");
                if (buffer != null) {
                    byte buffer4 = buffer[4];
                    byte buffer5 = buffer[5];
                    switch (buffer4) {
                        case 0x1a:
                            if (buffer5 == 0x39) { // 读取云彩
                                int dataLenght = buffer[7];
                                byte  value1 = buffer[8];//开关
                                byte  value2 = buffer[9];//开始小时
                                byte  value3 = buffer[10];//开始分钟
                                byte  value4 = buffer[11];//结束小时
                                byte  value5 = buffer[12];//结束分钟
                                byte  value6 = buffer[13];//速度
                                byte  value7 = buffer[14];//亮度
                                byte  value8 = buffer[15];//重复
//                                0x01(开)/0x00(关)
                                onoffvalue = value1;
                                if (value1==0x01){
                                    on_off.setChecked(true);
                                }else {
                                    on_off.setChecked(false);
                                }
                                starthour = value2;
                                starminute = value3;
                                endhour = value4;
                                endmimute = value5;
                                String  startHour=(value2<10)?("0"+value2):(""+value2);
                                String  startMinute=(value3<10)?("0"+value3):(""+value3);
                                String  EndHour=(value4<10)?("0"+value4):(""+value4);
                                String  EndMinute=(value5<10)?("0"+value5):(""+value5);
                                startTime=value2*60+value3;
                                endTime=value4*60+value5;
                                tv_start_time.setText(startHour+":"+startMinute);
                                tv_end_time.setText(EndHour+":"+EndMinute);
                                tv_strength_count.setText(value7+"%");
                                tv_speed_count.setText(value6+getString(R.string.greed));
                                sb_strength_seekbar.setProgress(value7);
                                sb_speed_seekbar.setProgress(value6-1);
//                                System.out.println("progress 星期0 :"+value8);
                                if((value8 & 1) == 1) {
                                    week_1 = true;
                                } else {
                                    week_1 = false;
                                }
                                if((value8 & 2) == 2) {
                                    week_2 = true;
                                } else {
                                    week_2 = false;
                                }
                                if((value8 & 4) == 4) {
                                    week_3 = true;
                                } else {
                                    week_3 = false;
                                }
                                if((value8 & 8) == 8) {
                                    week_4 = true;
                                } else {
                                    week_4 = false;
                                }
                                if((value8 & 16) == 16) {
                                    week_5 = true;
                                } else {
                                    week_5 = false;
                                }
                                if((value8 & 32) == 32) {
                                    week_6 = true;
                                } else {
                                    week_6 = false;
                                }
                                if((value8 & 64) == 64) {
                                    week_7 = true;
                                } else {
                                    week_7 = false;
                                }
                                buffers=new StringBuffer();
                                if (week_1)
                                    buffers.append(getString(R.string.week_1));
                                if (week_2)
                                    buffers.append(getString(R.string.week_2));
                                if (week_3)
                                    buffers.append(getString(R.string.week_3));
                                if (week_4)
                                    buffers.append(getString(R.string.week_4));
                                if (week_5)
                                    buffers.append(getString(R.string.week_5));
                                if (week_6)
                                    buffers.append(getString(R.string.week_6));
                                if (week_7)
                                    buffers.append(getString(R.string.week_7));
                                if (week_1&&week_2&&week_3&&week_4&&week_5&&week_6&&week_7){
                                    buffers=new StringBuffer();
                                    buffers.append(getString(R.string.week_all));
                                }
                                tv_repeat_content.setText(buffers);
                            }
                            break;
                        default:
                            break;
                    }
                }
            }
        }
    };


    private void showlaoddingwindow() {
        //设置contentView
        View contentView = LayoutInflater.from(this).inflate(R.layout.custom_progress_loading_dialog, null);
        mPopWindow = new PopupWindow(contentView,
                RelativeLayout.LayoutParams.MATCH_PARENT, RelativeLayout.LayoutParams.MATCH_PARENT, true);
        //显示PopupWindow
        View rootview = LayoutInflater.from(this).inflate(R.layout.cloudy_layout, null);
        mPopWindow.setOutsideTouchable(false);
        mPopWindow.setFocusable(false);
        mPopWindow.showAtLocation(rootview, Gravity.CENTER, 0, 0);
        uiHandle.sendEmptyMessageDelayed(1, 0);
    }

    //开启一个线程
    private Runnable runnable = new Runnable() {

        @Override
        public void run() {
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    mPopWindow.dismiss();
                }
            });
        }
    };

    Handler uiHandle = new Handler() {
        public void handleMessage(Message msg) {
            switch (msg.what) {
                //实现计时器功能
                case 1:
                    uiHandle.postDelayed(runnable, 300);
                    break;
                default:
                    break;
            }
        }
    };
}
